import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
* @description: 890. 查找和替换模式
* @author hewei
* @date 2022/9/15 16:22
* @version 1.0
*/

public class FindAndReplacePattern {

    public List<String> findAndReplacePattern(String[] words, String pattern) {
        List<String> ans = new ArrayList<>();
        for (String word : words) {
            if (word.length() != pattern.length()) continue;
            HashMap<Character, Character> map = new HashMap<>();
            HashSet<Character> set = new HashSet<>();
            boolean flag = true;
            for (int i = 0; i < pattern.length(); i++) {
                char c1 = word.charAt(i), c2 = pattern.charAt(i);
                if ((map.containsKey(c2) && map.get(c2) != c1) || (!map.containsKey(c2) && set.contains(c1))) {
                    flag = false;
                    break;
                }
                if (!map.containsKey(c2)) {
                    set.add(c1);
                    map.put(c2, c1);
                }
            }
            if (flag) ans.add(word);
        }
        return ans;
    }
}
